<template>
  <!-- 工作日志 -->
  <div class="project-type-work-log">
    <el-button type="primary" size="mini" @click="handleClickCreate" class="mb_12" v-if="isShowOperation">{{ $t('common.projectManage.detail.workLog.title1') }}</el-button>
    <el-table v-table-style v-loading="listLoading" :data="dataList" max-height="500" header-row-class-name="common-list-table-header__v2" border>
      <template slot="empty">
        <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>

      <el-table-column v-for="(column, index) in columns" :key="`${column.displayName}_${index}`" :prop="column.fieldName" :label="column.displayName" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="column.fieldName === 'workDate'">
            {{ scope.row[column.fieldName] | fmt_form_date }}
          </template>
          
          <template v-else-if="column.fieldName === 'createUserName'">
            {{ scope.row.createUserName }}
          </template>

          <template v-else-if="column.fieldName === 'createTime' || column.fieldName === 'updateTime'">
            {{ scope.row[column.fieldName] | fmt_datetime }}
          </template>
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="160">
        <template slot-scope="scope">
          <!-- 查看权限不受控制 -->
          <span class="operation-button edit" @click="handleViewWorkLog(scope.row)">{{ $t('common.base.view') }}</span>
          <template v-if="scope.row.createUserId === loginUserId && isShowOperation">
            <!-- 登陆人 和 当前创建人一致才显示操作 -->
            <span class="operation-button edit ml_12" @click="handleEditWorkLog(scope.row)">{{ $t('common.base.edit') }}</span>
            <span class="operation-button ml_12 delete" @click="handleDeleteWorkLog(scope.row)">{{ $t('common.base.delete') }}</span>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="project-type-work-log-footer" v-if="totalItems">
      <div class="total-count">
        <i18n path="common.base.table.totalCount">
          <span place="count">{{ totalItems }}</span>
        </i18n>
      </div>
      <el-pagination background @current-change="handleCurrentChange" :page-size="paginationInfo.pageSize" :current-page="paginationInfo.pageNum" layout="prev, pager, next" :total="totalItems"> </el-pagination>
    </div>

    <!-- 新建编辑工作日志弹框 -->
    <projectTypeWorkLogDialog ref="workLogDialogRef" :fields="allField" :form="form" @submitWorkLog="submitWorkLog" @updateWorkLog="updateWorkLog" :dialogTitleType="dialogTitleType" />

    <!-- 工作日志详情 -->
    <projectTypeWorkLogView ref="workLogViewRef" :fields="allField" :form="form"/>
  </div>
</template>
<script>
import { onMounted, reactive, toRefs, ref, set, computed } from 'vue';

import { MessageBox } from 'element-ui';
import appConfig from 'app.config';
import { toast } from '@src/util/platform';
import i18n from '@src/locales';
import moment from 'moment';

import { expandField, initialize } from '@src/component/form/util';

import { getProjectTypeField, workRecordList, workRecordCreate, workRecordUpdate, workRecordDelete, getWorkRecord } from '@src/api/ProjectManage.ts';
import projectTypeWorkLogDialog from './projectTypeWorkLogDialog.vue';
import projectTypeWorkLogView from './projectTypeWorkLogView.vue';

import { fixWorkLog } from '@src/modules/projectManage/productTypeUtils/fixFields.js';

export default {
  name: 'project-type-work-log',
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    projectId: {
      type: String | Number,
      default: '',
    },
    taskId: {
      type: String | Number,
      default: '',
    },
    // 权限
    btnAuth: {
      type: Object,
      default: () => ({}),
    },
    // 任务是否为取消状态 取消状态不展示操作
    isTaskCancelState: {
      type: Boolean,
      default: false
    }
  },
  components: {
    projectTypeWorkLogDialog,
    projectTypeWorkLogView,
  },
  setup(props) {
    const workLogDialogRef = ref();
    const workLogViewRef = ref();

    const state = reactive({
      listLoading: false,
      columns: [],
      allField: [],
      form: {},
      totalItems: 0,
      dataList: [],
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
      },
      dialogTitleType: 'new',
      // 获取登陆的userId
      loginUserId: localStorage.getItem('userId'),
      isShowBtn: false,
    });

    // 是否显示操作按钮
    const isShowOperation = computed(() => {
      return state.isShowBtn && props?.btnAuth?.isProjectMember && !props.isTaskCancelState;
    });
    // 获取表单字段
    const fetchWorkLogFields = async () => {
      state.listLoading = true;
      try {
        let ret = await getProjectTypeField({
          tableName: 'projectWorkLog',
          templateId: props.templateId,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.columns = [...(data || []), ...fixWorkLog].filter(f => f.formType !== 'attachment' && f.formType !== 'separator' && f.formType !== 'info' && f.formType !== 'autograph');
      } catch (err) {
        console.log('error => fetchWorkLogFields', err);
      } finally {
        state.listLoading = false;
      }
    };

    // 获取弹框表单字段
    const fetchWorkLogFieldsDialog = async () => {
      if (state.dialogTitleType !== 'view') {
        workLogDialogRef.value.formLoading = true;
      }
      state.allField = [];

      try {
        let ret = await getProjectTypeField({
          tableName: 'projectWorkLog',
          templateId: props.templateId,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        state.allField = (data || []).map(item => {
          return {
            ...item,
            // 说明限制500
            maxlength: item.fieldName == 'workContent' ? 500 : '',
          };
        });

        if (state.dialogTitleType == 'new') {
          state.form = initialize(data, {});
        }
      } catch (err) {
        console.log('error => fetchWorkLogFieldsDialog', err);
      } finally {
        if (state.dialogTitleType !== 'view') {
          workLogDialogRef.value.formLoading = false;
        }
      }
    };


    // 获取工作日志是否开启关闭的权限
    const fetchWorkLogAuth = () => {
      getWorkRecord({
        templateId: props.templateId,
      }).then(res => {
        const { success, data, message } = res;
        if (!success) return toast(message, 'error');

        state.isShowBtn = data?.status;
      });
    };

    // 获取数据
    const fetchTableList = async () => {
      state.listLoading = true;
      try {
        let res = await workRecordList({
          projectId: props.projectId,
          taskId: props.taskId,
          ...state.paginationInfo,
        });

        const { data, message, success } = res;

        if (!success) return toast(message, 'error');

        let { list = [], total = 0 } = data;

        state.dataList = list;
        state.totalItems = total;
      } catch (error) {
        console.warn('projectTypeWorkLog fetchTableList =>', error);
      } finally {
        state.listLoading = false;
      }
    };

    // 新建
    const handleClickCreate = () => {
      if (!workLogDialogRef.value) return;

      workLogDialogRef.value.openDialog();
      state.dialogTitleType = 'new';
      fetchWorkLogFieldsDialog();
    };

    // 编辑
    const handleEditWorkLog = row => {
      state.form = {
        ...row,
        ...row.attribute,
      };
      workLogDialogRef.value.openDialog();
      state.dialogTitleType = 'edit';
      fetchWorkLogFieldsDialog();
    };

    // 查看
    const handleViewWorkLog = row => {
      state.form = {
        ...row,
        ...row.attribute,
      };
      workLogViewRef.value.openDialog();
      state.dialogTitleType = 'view';
      fetchWorkLogFieldsDialog();
    }

    // 删除
    const handleDeleteWorkLog = ({ id }) => {
      MessageBox.confirm(i18n.t('common.projectManage.detail.workLog.deleteLogTip'), i18n.t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            workRecordDelete({ recordId: id }).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();

              fetchTableList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    };

    // 切换分页
    const handleCurrentChange = pageNum => {
      state.paginationInfo.pageNum = pageNum;
      fetchTableList();
    };

    /* form-builder更新事件 */
    const update = ({ field, newValue, oldValue }) => {
      let { fieldName = '', displayName = '' } = field || {};

      if (appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }

      set(state.form, fieldName, newValue);
    };

    const updateWorkLog = val => {
      update(val);
    };

    // 提交参数处理
    const paramsFunc = () => {
      const params = {
        projectId: props.projectId,
        taskId: props.taskId,
        attribute: {},
      };

      expandField(state.allField).forEach(element => {
        let { fieldName, isSystem, formType } = element;

        let value = state.form[fieldName];

        if (isSystem) {
          if (fieldName === 'workDate') {
            params[fieldName] = moment(value).valueOf();
          } else {
            params[fieldName] = value;
          }
        } else {
          params.attribute[fieldName] = value;
        }
      });

      return params;
    };

    // 提交
    const submitWorkLog = async () => {
      try {
        const params = paramsFunc();

        let url = '';
        if (state.dialogTitleType === 'edit') {
          url = workRecordUpdate({
            ...params,
            id: state.form?.id,
            deleteFiles: workLogDialogRef.value?.needServerDeleFiles || []
          });
        } else if (state.dialogTitleType === 'new') {
          url = workRecordCreate({ ...params });
        }

        let ret = await url;

        const { success, message } = ret;
        if (!success) return toast(message, 'error');

        toast(i18n.t('common.base.tip.createSuccess2'), 'success');
        fetchTableList();
        workLogDialogRef.value.closeDialog();
      } catch (error) {
        console.warn('submitWorkLog fetchTableList =>', error);
      } finally {
        console.log('wuwuwu');
        workLogDialogRef.value.showLoading = false;
      }
    };

    onMounted(() => {
      fetchWorkLogAuth();
      fetchTableList();
      fetchWorkLogFields();
    });

    return {
      workLogDialogRef,
      workLogViewRef,
      ...toRefs(state),
      handleViewWorkLog,
      handleClickCreate,
      handleEditWorkLog,
      handleDeleteWorkLog,
      handleCurrentChange,
      submitWorkLog,
      updateWorkLog,
      isShowOperation,
    };
  },
};
</script>
<style lang="scss" scoped>
.project-type-work-log {
  ::v-deep .el-button--mini {
    border-radius: 4px;
  }

  .operation-button {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
  .edit {
    color: $color-primary;
  }
  .delete {
    color: $color-danger;
  }
  .mr_12 {
    margin-right:12px;
  }
  &-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 12px;

    .total-count {
      font-size: 12px;
    }
  }
}
</style>